<?php

namespace IDock\Insurance\HBIC\Request;

use IDock\Http\RequestFormat;
use IDock\Insurance\HBIC\HBICEnums;
use IDock\Insurance\HBIC\Response\CommonResponse;
use IDock\Insurance\HBIC\Response\InsuranceOrderQueryResponse;
use IDock\Insurance\HBIC\Response\UploadFileResponse;
use IDock\Visitor\UploadFileVisitor;

/**
 * 影像上传接口
 */
class UploadFileRequest extends AllHBICRequest
{
    protected $response = UploadFileResponse::class;

    protected $urlTip = '影像资料上传接口';

    public $requestType = 'uploadFile';

    protected $resourceType = 'BXT';
    protected $inLog = true;

    public $format = RequestFormat::MUL;

    public $token = '';

    /**
     * @var UploadFileVisitor $visitor
     */
    protected $visitor;


    public function generate(): array
    {
        $imageList = $this->visitor->getFileList();
        $isNewCar = boolval($this->visitor->argc['isNewCar'] ?? '') ? '01' : '02';
        $val = $imageList[0];
        $tmp = [
            'bussNo' => $this->visitor->inquiryNo,
            'policyNo' => '',
            'typeSelect01' => '01',//承保
            'typeSelect02' => $this->visitor->argc['isNewCar'] ? '05' : '06',//05 新车
            'typeSelect03' => HBICEnums::$uploadImageType[$isNewCar][$val['type']] ?? '',
            'file' => \GuzzleHttp\Psr7\Utils::tryFopen($val['url'],'r'),
        ];
        $newCarName = $isNewCar == '01' ? '新车' : '旧车';
        $typeSelect03 = HBICEnums::$uploadImageTypeName[$isNewCar][$tmp['typeSelect03']] ?? '其他资料';
        $tmp['typePathName'] = '承保-'.$newCarName.'-'.$typeSelect03;
        $extArr = explode('.',$val['url']);
        $ext = end($extArr);
        $fileName = 'HB'.$this->resourceType.$tmp['typePathName']. '.'.$ext;
        $data = [];
        foreach ($tmp as $key => $value){
            $item = [
                'name' => $key,
                'contents' => $value,
            ];
            if($key == 'file'){
                $item['filename'] = $fileName;
            }
            $data[] = $item;
        }
        $data['token'] = 'Bearer '. $this->token;
        return $data;
    }

    private function getImageList()
    {
        $imgList = [];
        foreach ($this->visitor->getFileList() as $val){
            $baseName = basename($val['url']);
            $ext = explode('.',$baseName);
            $imgList[] = [
                'imgName' => $baseName,//要求英文
                'base64Img' => base64_encode(file_get_contents($val['url'])),//图片base64编码
                'filedSuffix' => $ext[1] ?? '',//文件后缀
//                'filedPath' => $val['url'],//图片地址 ftp模式必传
            ];
        }
        return $imgList;
    }


}
